import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import { getToken } from './auth/getToken.js';
import { getProjects } from './services/Project/getProjects.js';
import { getProducts } from './services/Product/getProducts.js';
import { getDevices } from './services/Device/getDevices.js';
import { addDevice } from './services/Device/addDevice.js';
import { getMyProject } from './auth/projectStore.js';
import { startDeviceShadowPolling } from './services/Device/getDeviceShadow.js';
import mysql from 'mysql2/promise';

// 加载 .env 文件
dotenv.config();

// 创建数据库连接池
const pool = mysql.createPool({
  host: process.env.DB_HOST,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

// 创建 Express 应用
const app = express();

// 使用 cors 中间件
app.use(cors());

// 解析 JSON 请求体
app.use(express.json());

// 定义一个简单的路由
app.get('/', (req, res) => {
  res.send('Hello World!');
});

// 新增 /login 路由
app.post('/login', async (req, res) => {
  try {
    const token = await getToken();
    res.status(200).json({ token });
  } catch (error) {
    console.error('Failed to retrieve token during login:', error);
    res.status(500).json({ error: 'Failed to retrieve token' });
  }
});

// 新增 /projects 路由
app.get('/projects', async (req, res) => {
  try {
    const projects = await getProjects();
    res.status(200).json(projects);
  } catch (error) {
    console.error('Failed to retrieve projects:', error);
    res.status(500).json({ error: 'Failed to retrieve projects' });
  }
});

// 新增 /products 路由
app.get('/products', async (req, res) => {
  try {
    // 检查项目 ID 是否已设置
    const projectId = getMyProject();
    if (!projectId) {
      throw new Error('Project ID not set. Please call /projects first.');
    }

    const products = await getProducts();
    res.status(200).json(products);
  } catch (error) {
    console.error('Failed to retrieve products:', error);
    res.status(500).json({ error: error.message });
  }
});

// 新增 /devices 路由
app.get('/devices', async (req, res) => {
  try {
    // 检查项目 ID 是否已设置
    const projectId = getMyProject();
    if (!projectId) {
      throw new Error('Project ID not set. Please call /projects first.');
    }

    const devices = await getDevices();
    res.status(200).json(devices);
  } catch (error) {
    console.error('Failed to retrieve devices:', error);
    res.status(500).json({ error: error.message });
  }
});

// 新增 /devices 路由 - POST 方法
app.post('/devices', async (req, res) => {
  try {
    // 检查项目 ID 是否已设置
    const projectId = getMyProject();
    if (!projectId) {
      throw new Error('Project ID not set. Please call /projects first.');
    }

    // 获取请求体中的设备数据
    const deviceData = req.body;

    // 打印请求体内容以便调试
    console.log('Received device data:', deviceData);

    // 验证请求体是否存在且不为空
    if (!deviceData || Object.keys(deviceData).length === 0) {
      throw new Error('Device data is missing or empty in the request body');
    }

    // 验证设备数据的必要字段
    const requiredFields = ['product_id', 'device_id', 'node_id'];
    const missingFields = requiredFields.filter(field => !deviceData[field]);
    if (missingFields.length > 0) {
      throw new Error(`Missing required fields: ${missingFields.join(', ')}`);
    }

    // 调用 addDevice 函数添加设备
    const newDevice = await addDevice(deviceData);

    res.status(201).json(newDevice);
  } catch (error) {
    console.error('Failed to add device:', error);
    res.status(500).json({ error: error.message });
  }
});

// 新增 /temperature 路由
app.get('/temperature', async (req, res) => {
  try {
    const connection = await pool.getConnection();
    try {
      const [rows] = await connection.query(
        'SELECT property_value FROM device_properties WHERE property_name = ? ORDER BY device_id DESC, property_name DESC LIMIT 1',
        ['Home_Temperature']
      );
      if (rows.length === 0) {
        throw new Error('No temperature data found');
      }
      const temperature = JSON.parse(rows[0].property_value);
      res.status(200).json({ temperature });
    } finally {
      connection.release();
    }
  } catch (error) {
    console.error('Failed to retrieve temperature:', error);
    res.status(500).json({ error: error.message });
  }
});

// 新增 /humidity 路由
app.get('/humidity', async (req, res) => {
  try {
    const connection = await pool.getConnection();
    try {
      const [rows] = await connection.query(
        'SELECT property_value FROM device_properties WHERE property_name = ? ORDER BY device_id DESC, property_name DESC LIMIT 1',
        ['Home_Humidity']
      );
      if (rows.length === 0) {
        throw new Error('No humidity data found');
      }
      const humidity = JSON.parse(rows[0].property_value);
      res.status(200).json({ humidity });
    } finally {
      connection.release();
    }
  } catch (error) {
    console.error('Failed to retrieve humidity:', error);
    res.status(500).json({ error: error.message });
  }
});

// 新增 /smoke 路由
app.get('/smoke', async (req, res) => {
  try {
    const connection = await pool.getConnection();
    try {
      const [rows] = await connection.query(
        'SELECT property_value FROM device_properties WHERE property_name = ? ORDER BY device_id DESC, property_name DESC LIMIT 1',
        ['Smoke']
      );
      if (rows.length === 0) {
        throw new Error('No smoke data found');
      }
      const smoke = JSON.parse(rows[0].property_value);
      res.status(200).json({ smoke });
    } finally {
      connection.release();
    }
  } catch (error) {
    console.error('Failed to retrieve smoke:', error);
    res.status(500).json({ error: error.message });
  }
});

// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, async () => {
  console.log(`Server is running on port ${PORT}`);

  // 创建数据表
  try {
    const connection = await pool.getConnection();
    

    // 创建 device_shadow 表
    await connection.query(`
      CREATE TABLE IF NOT EXISTS device_shadow (
        device_id VARCHAR(255) PRIMARY KEY,
        properties JSON NOT NULL
      )
    `);

    // 创建 device_properties 表，移除 id 列，改为 (property_name, device_id) 主键
    await connection.query(`
      CREATE TABLE IF NOT EXISTS device_properties (
        property_name VARCHAR(255) NOT NULL,
        property_value TEXT NOT NULL,
        device_id VARCHAR(255),
        PRIMARY KEY (property_name, device_id)
        
      )
`);

    // 删除操作改为基于 (property_name, device_id) 的清理逻辑
    await connection.query(`
      DELETE FROM device_properties 
      WHERE (property_name, device_id) NOT IN (
        SELECT property_name, device_id FROM (
          SELECT property_name, device_id FROM device_properties ORDER BY property_name DESC, device_id DESC LIMIT 10
        ) AS latest_records
      )
`);

    connection.release();
  } catch (error) {
    console.error('Failed to create tables:', error);
  }

  // 在服务器启动后调用 startDeviceShadowPolling
  try {
    // 假设设备 ID 为 'testDeviceId'，实际使用时应从配置或数据库中获取
    const deviceId = '67c6f14080c3872914af9de6_Smart_Home';
    startDeviceShadowPolling(deviceId, (error, shadowData) => {
      if (error) {
        console.error('Error in device shadow polling:', error);
      } else {
        console.log('Device shadow data received:', shadowData);
      }
    });
  } catch (error) {
    console.error('Failed to start device shadow polling:', error);
  }
});
